package com.hzspace.single;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author: LiuHao
 * @Descirption:
 * @Date: 2020/3/2_15:49
 */
@Service
public class UserService {
    @Autowired
    JdbcTemplate jdbcTemplate;

    public Integer insertUser(User user){
        return jdbcTemplate.update("insert into user (username, address) values (?, ?);", user.getUsername(), user.getAddress());
    }

    public Integer updateUser(User user){
        return jdbcTemplate.update("update user set username = ? where id=?;", user.getUsername(), user.getId());
    }

    public Integer deleteUserById(Integer id){
        return jdbcTemplate.update("delete from user where id=?", id);
    }

    public Object findAll(){
        return jdbcTemplate.query("select * from user", new RowMapper<Object>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setUsername(resultSet.getString("username"));
                user.setAddress(resultSet.getString("address"));
                return user;
            }
        });
    }

    public Object findAll2(){
        //BeanPropertyRowMapper这种方式字段名必须一一对应
        return jdbcTemplate.query("select * from user", new BeanPropertyRowMapper<>(User.class));
    }

    public Object findOne(Integer id){
        //BeanPropertyRowMapper这种方式字段名必须一一对应
        //queryForObject查询结果集list不为Empty且size==1 否则会抛异常
        return jdbcTemplate.queryForObject("select * from user where id=?", new BeanPropertyRowMapper<>(User.class), id);
    }
}
